﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;

namespace mSpy.UI
{
    public class SpyServer
    {
        private TcpListener _listener;
        private Thread _thread;

        public SpyServer(IPAddress ip, int port)
        {
            this._listener = new TcpListener(ip, port);
            this._thread = new Thread(new ThreadStart(WaitForClients));
        }

        public void Start()
        {
            this._thread.Start();
        }

        public void Kill()
        {
            if (_thread != null) { _thread.Abort(); }
            if (_listener != null) { _listener.Stop(); }
        }

        private void WaitForClients()
        {
            this._listener.Start();

            while (true)
            {
                TcpClient client = this._listener.AcceptTcpClient();

                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleIncomingConnection));
                clientThread.Start(client);
            }
        }

        private void HandleIncomingConnection(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();

            byte[] message = new byte[4096];
            int bytesRead;

            while (true)
            {
                bytesRead = 0;
                try
                {
                    bytesRead = clientStream.Read(message, 0, 4096);
                }
                catch { break; }

                if (bytesRead == 0) { break; }

                ASCIIEncoding encoder = new ASCIIEncoding();
                OnMessage(new SpyEvents { Message = encoder.GetString(message, 0, bytesRead) });
            }

            tcpClient.Close();
        }

        public delegate void SpyEventHandler(object sender, SpyEvents e);
        public event SpyEventHandler Message;

        protected void OnMessage(SpyEvents e)
        {
            if (Message != null)
            {
                Message(this, e);
            }
        }
    }
}
